import { useEffect, useState } from 'react'
import { View } from '@tarojs/components'
import F2Canvas from 'taro-f2-react'
import { Chart, Line, Axis, Point, Legend, Area } from '@antv/f2'

interface IRadarChartsProps {
  id?: string
  data?: any[]
  fieldNames?: {
    [key: string]: string
  }
  fontSize?: number
  color?: any
}

const IRadarChartsIndex: React.FC<IRadarChartsProps> = props => {
  const {
    id,
    data = [],
    fieldNames = { label: 'name', value: 'totalNum' },
    fontSize = 12,
    color = '#7c86b4'
  } = props

  const [maxScore, setMaxScore] = useState<number>(30)

  const sourceData =
    data?.map(item => ({
      ...item,
      [fieldNames.value]: parseInt(item[fieldNames.value])
    })) || []

  useEffect(() => {
    if (data.length > 0) setMaxScore(data[0].score)
  }, [data])

  return (
    <View style={{ width: '100%', height: '260px' }} className='chart_body'>
      {sourceData.length > 0 ? (
        <F2Canvas id={id}>
          <Chart
            data={sourceData}
            coord='polar'
            scale={{
              score: {
                min: 0,
                max: maxScore,
                nice: false,
                tickCount: 4
              }
            }}
          >
            <Axis
              field={fieldNames.label}
              grid='line'
              formatter={(value, index) =>
                `${value} (${sourceData[index].type})`
              }
              style={{ label: { fontSize, fontWeight: 500 } }}
              color={color}
            />
            <Axis field={fieldNames.value} grid='line' color={color} />
            <Line x={fieldNames.label} y={fieldNames.value} color={color} />
            <Area x={fieldNames.label} y={fieldNames.value} color={color} />
            <Point x={fieldNames.label} y={fieldNames.value} color={color} />
            <Legend />
          </Chart>
        </F2Canvas>
      ) : null}
    </View>
  )
}

export default IRadarChartsIndex
